// 基础API服务配置
const API_BASE_URL = 'http://localhost:3002/api'; // 本地开发服务器API基础URL

// 请求拦截器配置
function requestInterceptor(config) {
  // 添加认证token
  const token = wx.getStorageSync('token');
  if (token) {
    config.header.Authorization = `Bearer ${token}`;
  }
  return config;
}

// 响应拦截器配置
function responseInterceptor(response) {
  // 处理常见错误
  if (response.statusCode === 401) {
    // 未授权，跳转登录
    wx.navigateTo({ url: '/pages/login/login' });
    return Promise.reject(new Error('未授权，请重新登录'));
  }
  return response.data;
}

// 基础请求方法
function request(options) {
  // 默认配置
  const defaultOptions = {
    url: API_BASE_URL + options.url,
    method: options.method || 'GET',
    header: {
      'Content-Type': 'application/json',
      ...options.header
    },
    data: options.data || {},
    timeout: 10000
  };

  // 应用请求拦截器
  const config = requestInterceptor(defaultOptions);

  return new Promise((resolve, reject) => {
    wx.request({
      ...config,
      success: (res) => {
        try {
          const processedData = responseInterceptor(res);
          resolve(processedData);
        } catch (error) {
          reject(error);
        }
      },
      fail: (error) => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
        reject(error);
      }
    });
  });
}

// 封装常用请求方法
module.exports = {
  get: (url, data, options = {}) => request({ url, data, method: 'GET', ...options }),
  post: (url, data, options = {}) => request({ url, data, method: 'POST', ...options }),
  put: (url, data, options = {}) => request({ url, data, method: 'PUT', ...options }),
  delete: (url, data, options = {}) => request({ url, data, method: 'DELETE', ...options })
};